import Header from './components/header/Header.js';
import TopicInput from './components/header/TopicInput.js';
import ControlButtons from './components/header/ControlButtons.js';
import CharacterPanel from './components/character-panel/CharacterPanel.js';
import CharacterCard from './components/character-panel/CharacterCard.js';
import ChatArea from './components/chat-area/ChatArea.js';
import MessageBubble from './components/chat-area/MessageBubble.js';
import SettingsPanel from './components/settings-panel/SettingsPanel.js';
import CharacterSettings from './components/settings-panel/CharacterSettings.js';
import VoiceSettings from './components/settings-panel/VoiceSettings.js';
import CharacterModal from './components/modals/CharacterModal.js';
import apiService from './utils/api.js';

// 初始化应用
class App {
  constructor() {
    this.api = apiService;
    this.initComponents();
    this.setupEventListeners();
    this.loadInitialData();
  }

  async loadInitialData() {
    try {
      // 初始化ChatArea
      await this.chatArea.init();

      // 从本地获取所有角色数据
      const localData = await apiService.getLocalCharacterData();

      // 确保数据是数组
      const localDataList = Array.isArray(localData) ? localData : [];

      // 渲染所有角色面板
      localDataList.forEach(data => {
        if (data && typeof data === 'object') {
          this.characterPanel.addCharacter(data);
        }
      });
    } catch (error) {
      console.error('加载本地角色面板数据失败:', error);
    }
  }


  initComponents() {
    // 初始化header
    this.header = new Header(
      this.handleTopicChange.bind(this),
      this.handleStart.bind(this),
      this.handlePause.bind(this),
      this.handleResume.bind(this),
      this.handleRestart.bind(this),
      this.handleNextRound.bind(this),
      this.chatArea
    );
    const headerContainer = document.getElementById('header');
    headerContainer.innerHTML = ''; // 清空容器
    headerContainer.appendChild(this.header.render());

    // 初始化character panel
    // 创建CharacterPanel实例，用于展示和管理角色
    // 传递事件处理函数以实现添加和选择角色的功能
    this.characterPanel = new CharacterPanel(
      this.handleAddCharacter.bind(this),
      this.handleSelectCharacter.bind(this)
    );

    // 获取角色面板容器的DOM元素
    const characterPanelContainer = document.getElementById('character-panel');

    // 清空角色面板容器的内容，为加载新的面板做准备
    characterPanelContainer.innerHTML = '';

    // 将角色面板组件渲染到DOM中，并添加到角色面板容器中
    characterPanelContainer.appendChild(this.characterPanel.render());


    // 初始化chat area
    this.chatArea = new ChatArea(this.handleSendMessage.bind(this));
    const chatAreaContainer = document.getElementById('chat-area');
    chatAreaContainer.innerHTML = '';
    chatAreaContainer.appendChild(this.chatArea.render());

    // 初始化settings panel
    this.settingsPanel = new SettingsPanel(
      this.handleCharacterSettingsChange.bind(this),
      this.handleVoiceSettingsChange.bind(this),
      null,
      this.handleUserSettingsChange.bind(this)
    );
    const settingsPanelContainer = document.getElementById('settings-panel');
    settingsPanelContainer.innerHTML = '';
    settingsPanelContainer.appendChild(this.settingsPanel.render());

    // 初始化modal
    this.characterModal = new CharacterModal(
      this.handleSaveCharacter.bind(this),
      this.handleCancelCharacter.bind(this)
    );
  }

  setupEventListeners() {
    // 添加全局事件监听
  }

  // 事件处理函数
  handleTopicChange(topic) {
    console.log('话题已更改:', topic);
    // 更新状态为准备中
    this.chatArea.debateState.status = 'ready';
    this.header.updateControls('ready');
  }

  handleStart() {
    console.log('开始辩论');
    // 获取当前话题
    const topic = this.header.getCurrentTopic();
    if (!topic) {
      alert('请先输入辩论话题');
      return;
    }

    // 开始辩论
    this.chatArea.startDebate(topic);
    this.chatArea.debateState.status = 'in_progress';
    this.header.updateControls('in_progress');
    this.header.setStatus('in_progress');
  }

  handlePause() {
    console.log('暂停辩论');
    console.log('当前状态:', this.chatArea.debateState);
    this.chatArea.debateState.status = 'paused';
    this.chatArea.clearNextRoundTimer();
    // 启用下一轮按钮
    this.header.setButtonDisabled('next', false);
    this.header.updateControls('paused');
    this.header.setStatus('paused');
    console.log('暂停后状态:', this.chatArea.debateState);
  }

  async handleResume() {
    console.log('继续辩论');
    this.chatArea.debateState.status = 'in_progress';
    this.header.updateControls('in_progress');
    this.header.setStatus('in_progress');
    // 继续当前角色的发言
    await this.chatArea.nextRound();
  }

  async handleRestart() {
    console.log('重启辩论');
    this.chatArea.debateState = {
      status: 'idle',
      currentSpeaker: null,
      round: 0,
      topic: null
    };
    this.header.updateControls('idle');
    this.header.setStatus('idle');
    // 清空聊天记录
    this.chatArea.messagesContainer.innerHTML = '';
    // 清除角色会话历史
    await this.api.clearCharacterHistory();
  }

  async handleNextRound() {
    if (this.chatArea.debateState.status === 'paused') {
      // 手动模式下执行下一轮
      await this.chatArea.nextRound();
      // 保持暂停状态
      this.chatArea.debateState.status = 'paused';
      // 更新按钮状态
      this.header.updateControls('paused');
    }
  }

  handleAddCharacter() {
    this.characterModal.show();
  }

  handleSelectCharacter(character) {
    console.log('选择角色:', character);
    // 更新当前选中的角色设置
    this.settingsPanel.updateCharacterSettings(character);
  }

  async handleSendMessage(message) {
    console.log('发送消息:', message);
    // 获取头像
    const avatar = await this.getAvatarForSender(message.sender);
    // 将消息添加到聊天区域
    this.chatArea.addMessage({
      sender: message.sender,
      content: message.content,
      timestamp: message.timestamp,
      avatar: avatar
    });

    // 如果是用户发言且辩论进行中，自动触发下一轮
    if (message.sender === 'user' &&
      this.chatArea.debateState.status === 'in_progress') {
      this.chatArea.clearNextRoundTimer();
      await new Promise(resolve => setTimeout(resolve, 2000)); // 等待2秒
      if (this.chatArea.debateState.status === 'in_progress') {
        await this.chatArea.nextRound(); // 确保 nextRound() 执行完成
      }
    }
  }

  async getAvatarForSender(sender) {
    if (sender === 'user') {
      return this.chatArea.userSettings?.avatar ||
        'assets/images/default-avatar.png';
    }
    // 根据发言角色获取对应的头像
    try {
      const settings = await this.api.getCharacterSettings(sender);
      return settings?.avatar || 'assets/images/default-avatar.png';
    } catch (error) {
      console.error('获取角色头像失败:', error);
      return 'assets/images/default-avatar.png';
    }
  }

  handleCharacterSettingsChange(index, settings) {
    console.log('角色设置已更改:', index, settings);
    // 更新角色面板中的角色信息
    this.characterPanel.updateCharacter(index, settings);
  }

  handleVoiceSettingsChange(settings) {
    console.log('语音设置已更改:', settings);
  }

  handleUserSettingsChange(settings) {
    console.log('用户设置已更改:', settings);
    // 更新聊天区域中的用户头像和名称
    this.chatArea.updateUserSettings(settings);
  }

  handleSaveCharacter(characterData) {
    console.log('保存角色:', characterData);
    this.characterPanel.addCharacter(characterData);
    this.characterModal.hide();
  }

  handleCancelCharacter() {
    console.log('取消角色编辑');
    this.characterModal.hide();
  }
}

// 启动应用
new App();
